const express = require("express")
const path = require('path')
const user = require("./router/User")
const essay = require("./router/essay")
const mysql = require("./mysql/index")
const app = express()
const jwt = require("./util/JWTConfig")
const socketIo = require("socket.io"); // 导入 socket.io
const http = require("http")
const cors = require("cors"); // 导入 cors 模块
const resultClass = require("./dto/result")
mysql.connection()// 连接数据库
mysql.createTables()
// // 处理跨域中间件
// const corsHandler = (req, res, next) => {
//     // res.header('Access-Control-Allow-Origin', '*');
//     // res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
//     // res.header('Access-Control-Allow-Headers', 'Content-Type');
//     // res.header('Content-Type', 'text/plain; charset=utf-8');
//     // res.header("Access-Control-Allow-Credentials", "true");
//     // next();
// }
// 处理跨域中间件
const corsOptions = {
    origin: '*',
    methods: 'GET, POST, PUT, DELETE',
    allowedHeaders: '*',
    credentials: true,
};

// 过滤校验token 的 接口
const noVerifyTokenInterface = (path='')=>{
    console.log("接收的请求",path);
    if(path.includes('api/user/login') || path.includes('api/user/register')){
        return false
    }
    return true
}

// 检测token
const verifyToken = (req,res,next)=>{
    if(req.path.includes('api')) {
        //  如果是api请求，检验token
        if(!req.headers["token"]&& noVerifyTokenInterface(req.path)){
            const resultData = new resultClass(101,[])
            res.end(resultData)
            return
        }
        if(req.path.startsWith("/assets")||req.path.startsWith("/index.html")){
            next()
            return
        }
        if(req.headers["token"]){
            const userInfo = jwt.verifyToken(req.headers["token"])
            if(!userInfo){
                const resultData = new resultClass(100,[])
                res.end(JSON.stringify(resultData))
            }
            // console.log("根据token获取用户信息",userInfo);
            req.userInfo = userInfo
        }
    }
    next()
}

app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cors(corsOptions))
// 设置正确的字符集
// app.use(corsHandler);
app.use(verifyToken)
app.use("/api/user", user)

app.use("/api/essay", essay)
// 将静态资源目录指定为一个包含文件夹的路径
// console.log(path.join(__dirname, 'public'),"完整路径");
app.use(express.static('public'));

// 处理根路径的请求，发送 index.html 文件
app.get('/**', (req, res) => {
    console.log("path.join(__dirname, 'public', 'index.html')",path.join(__dirname, 'public', 'index.html'));
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
const server = http.createServer(app)
const io = socketIo(server,{
    cors: corsOptions  // 将socket.io的cors设置与express的保持一致
})

io.on("connection", socket=>{
    // console.log("用户已连接socket",socket);
    socket.on("message",message =>{
        console.log(message,"接收到消息");
        io.emit('resMsg',message)
    })
})

// 处理所有非 API 请求，返回 index.html
// app.get('*', (req, res) => {
//     res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
// });

server.listen("9000", () => {
    console.log('服务器正在运行，访问地址：http://localhost:9000');
});